package com.ruirenyun.util.oss;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.ResponseHeaderOverrides;
import com.ruirenyun.entity.constant.SYS;
import com.ruirenyun.util.common.DateUtil;
import com.ruirenyun.util.common.Precondition;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URL;
import java.security.SecureRandom;
import java.util.Date;
import java.util.Objects;

/**
 * @author Deng Ye
 * @date 2020/12/25
 * @description
 * @modifiedBy
 * @version: 1.0
 */
public class OssUtil {
    private static final Logger log = LogManager.getLogger(OssUtil.class);
    /**
     * OSS相关信息
     */
    private static final String ENDPOINT = "http://oss-cn-shanghai.aliyuncs.com";

    private static AliyunConfig aliyunConfig;

    private OssUtil() {
    }

    public static void setAliyunConfig(AliyunConfig config) {
        aliyunConfig = config;
    }

    public static OSS getOssClient() {
        String accessKeyId = aliyunConfig.getAccessKeyId();
        String accessKeySecret = aliyunConfig.getAccessKeySecret();
        return new OSSClientBuilder().build(ENDPOINT, accessKeyId, accessKeySecret);
    }

    public static String getOssUrlOfFile(String fileName) {
        if (StringUtils.isEmpty(fileName)) {
            return null;
        }
        OSS oss = null;
        //获取oss客户端
        try {
            oss = getOssClient();
            String bucketName = aliyunConfig.getBucketName();
            //获取url
            URL url = oss.generatePresignedUrl(bucketName, fileName, new Date(System.currentTimeMillis() + 300000));
            return url.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (Objects.nonNull(oss)) {
                oss.shutdown();
            }
        }
        return null;
    }
    public static String getOssUrlOfFile(String fileName,Date date) {
        if (StringUtils.isEmpty(fileName)) {
            return null;
        }
        OSS oss = null;
        //获取oss客户端
        try {
            oss = getOssClient();
            String bucketName = aliyunConfig.getBucketName();
            //获取url
            URL url = oss.generatePresignedUrl(bucketName, fileName, date);
            return url.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (Objects.nonNull(oss)) {
                oss.shutdown();
            }
        }
        return null;
    }

    /**
     * 功能描述 指定下载文件名
     * String downloadFileName
     *
     * @date 2020/9/8 16:03
     */
    public static String getOssUrlOfFile(String fileName, String downloadFileName) {
        if (StringUtils.isEmpty(fileName)) {
            return null;
        }
        OSS oss = null;
        //获取oss客户端
        try {
            oss = getOssClient();
            String bucketName = aliyunConfig.getBucketName();
            //设置下载文件名
            ResponseHeaderOverrides headerOverrides = new ResponseHeaderOverrides();
            headerOverrides.setContentDisposition("attachment; filename=" + downloadFileName);
            //请求方式
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, fileName, HttpMethod.GET);
            //过期时间
            Date expiration = new Date(System.currentTimeMillis() + 300000);
            request.setExpiration(expiration);
            request.setResponseHeaders(headerOverrides);
            //生成URL
            URL url = oss.generatePresignedUrl(request);
            return url.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (Objects.nonNull(oss)) {
                oss.shutdown();
            }
        }
        return null;
    }

    /**
     * 功能描述 指定下载文件名
     * String downloadFileName
     *
     * @date 2020/9/8 16:03
     */
    public static String getOssUrlOfFile(String fileName, String downloadFileName, Date date) {
        if (StringUtils.isEmpty(fileName)) {
            return null;
        }
        OSS oss = null;
        //获取oss客户端
        try {
            oss = getOssClient();
            String bucketName = aliyunConfig.getBucketName();
            //设置下载文件名
            ResponseHeaderOverrides headerOverrides = new ResponseHeaderOverrides();
            headerOverrides.setContentDisposition("attachment; filename=" + downloadFileName);
            //请求方式
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, fileName, HttpMethod.GET);
            //过期时间
            request.setExpiration(date);
            request.setResponseHeaders(headerOverrides);
            //生成URL
            URL url = oss.generatePresignedUrl(request);
            return url.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (Objects.nonNull(oss)) {
                oss.shutdown();
            }
        }
        return null;
    }

    /**
     * 功能描述 上传文件
     *
     * @param file
     * @author Deng Ye
     * @date 2020/9/8 16:03
     */
    public static OssRespVo uploadFile(MultipartFile file) {
        OSS oss = null;
        Precondition.checkNotNull(file, SYS.E10004.name());
        try (InputStream inputStream = file.getInputStream()) {
            oss = getOssClient();
            String name = file.getOriginalFilename();
            String suffix = name.substring(name.lastIndexOf("."));
            SecureRandom secureRandom = new SecureRandom();
            String fileName = aliyunConfig.getResource() + DateUtil.getNowDate("yyyyMMdd") + "/" + DateUtil.getNowDate("yyyyMMddHHmmsss") + "-" + secureRandom.nextInt(1000) + suffix;
            String bucketName = aliyunConfig.getBucketName();
            oss.putObject(bucketName, fileName, inputStream);
            //获取url
            URL url = oss.generatePresignedUrl(bucketName, fileName, new Date(System.currentTimeMillis() + 300000));
            return new OssRespVo(fileName, url.toString());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        } finally {
            if (Objects.nonNull(oss)) {
                oss.shutdown();
            }
        }
    }

    /**
     * 功能描述 上传文件
     */
    public static OssPublicRespVo uploadPublicFile(MultipartFile file) {
        OSS oss = null;
        Precondition.checkNotNull(file, SYS.E10004.name());
        try (InputStream inputStream = file.getInputStream()) {
            oss = getOssClient();
            String name = file.getOriginalFilename();
            String suffix = name.substring(name.lastIndexOf("."));
            SecureRandom secureRandom = new SecureRandom();
            String fileName = aliyunConfig.getResource() + DateUtil.getNowDate("yyyyMMdd") + "/" + DateUtil.getNowDate("yyyyMMddHHmmsss") + "-" + secureRandom.nextInt(1000) + suffix;
            String bucketName = aliyunConfig.getBucketName();
            oss.putObject(bucketName, fileName, inputStream);
            oss.setObjectAcl(aliyunConfig.getBucketName(),fileName, CannedAccessControlList.PublicRead);
            //获取url
            URL url = oss.generatePresignedUrl(bucketName, fileName, new Date(System.currentTimeMillis() + 300000));
            String s = url.toString();
            s = s.substring(0, s.indexOf('?'));

            return new OssPublicRespVo(name, fileName,s);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        } finally {
            if (Objects.nonNull(oss)) {
                oss.shutdown();
            }
        }
    }

    /**
     * 功能描述 上传文件 文件流
     *
     * @param inputStream
     * @author Deng Ye
     * @date 2020/9/8 16:03
     */
    public static OssRespVo uploadFile(InputStream inputStream, String name) {
        OSS oss = null;
        try {
            oss = getOssClient();
            SecureRandom secureRandom = new SecureRandom();
            String fileName = aliyunConfig.getResource() + DateUtil.getNowDate("yyyyMMdd") + "/" + DateUtil.getNowDate("yyyyMMddHHmmsss") + "-" + secureRandom.nextInt(1000) + "-" + name;
            String bucketName = aliyunConfig.getBucketName();
            oss.putObject(bucketName, fileName, inputStream);
            //获取url
            URL url = oss.generatePresignedUrl(bucketName, fileName, new Date(System.currentTimeMillis() + 300000));
            return new OssRespVo(fileName, url.toString());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        } finally {
            if (Objects.nonNull(oss)) {
                oss.shutdown();
            }
        }
    }

    /**
     * 功能描述 上传文件 文件流
     *
     * @param inputStream
     * @author Deng Ye
     * @date 2020/9/8 16:03
     */
    public static OssRespVo uploadFile(InputStream inputStream, String name, Date expire) {
        OSS oss = null;
        try {
            oss = getOssClient();
            SecureRandom secureRandom = new SecureRandom();
            String fileName = aliyunConfig.getResource() + DateUtil.getNowDate("yyyyMMdd") + "/" + DateUtil.getNowDate("yyyyMMddHHmmsss") + "-" + secureRandom.nextInt(1000) + "-" + name;
            String bucketName = aliyunConfig.getBucketName();
            oss.putObject(bucketName, fileName, inputStream);
            //获取url
            URL url = oss.generatePresignedUrl(bucketName, fileName, expire);
            return new OssRespVo(fileName, url.toString());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        } finally {
            if (Objects.nonNull(oss)) {
                oss.shutdown();
            }
        }
    }


    /**
     * 功能描述 上传文件
     *
     * @param file
     * @author Deng Ye
     * @date 2020/9/8 16:03
     */
    public static OssRespVo uploadFile(MultipartFile file, Date expire) {
        OSS oss = null;
        try (InputStream inputStream = file.getInputStream()) {
            oss = getOssClient();
            String name = file.getOriginalFilename();
            assert name != null;
            Precondition.checkArgument(StringUtils.isNotEmpty(file.getOriginalFilename()), SYS.E10004.name());
            String suffix = name.substring(name.lastIndexOf("."));
            SecureRandom secureRandom = new SecureRandom();
            String fileName = aliyunConfig.getResource() + DateUtil.getNowDate("yyyyMMdd") + "/" + DateUtil.getNowDate("yyyyMMddHHmmsss") + "-" + secureRandom.nextInt(1000) + suffix;
            String bucketName = aliyunConfig.getBucketName();
            oss.putObject(bucketName, fileName, inputStream);
            //获取url
            URL url = oss.generatePresignedUrl(bucketName, fileName, expire);
            return new OssRespVo(fileName, url.toString());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        } finally {
            if (Objects.nonNull(oss)) {
                oss.shutdown();
            }
        }
    }
}
